<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

class FmwKuaishouController extends Controller
{
    protected $baseUrl = '/api/kuaishou/';

    protected $requestData = [];

    public function index(Request $request)
    {
        $url = $request->get('s');
        $methodUrl = str_replace($this->baseUrl, '', $url);
        $method = str_replace('/', '_', $methodUrl);

        if (!method_exists($this, $method)) {
            echo sprintf("[%s] mock function not exists", $method);
            exit;
        }

        $this->requestData = $request->toArray();
        return $this->$method($request);
    }

    public function oauth2_access_token()
    {
//        return [
//            'result' => 100200101,
//            'error' => 'unauthorized_client',
//            'error_msg' => 'invalid appId'
//        ];
        return [
            'result' => 1,
            'access_token' => '888888',
            'refresh_token' => '123456',
            'open_id' => 'ks999',
            'expires_in' => 172800,
            'scopes' => ''
        ];
    }

    public function open_item_get(Request $request)
    {
        $params = json_decode($this->requestData['param'], true);
        $itemId = $params['kwaiItemId'] ?? 0;
        if ($itemId != '133734841781257') {
            return [
                'result' => 0,
                'error_msg' => '商品不存在',
                'code' => '100002',
                'msg' => '商品不存在',
                'sub_code' => '100002',
                'sub_msg' => '商品不存在'
            ];
        }

        return [
            'result' => 1,
            'data' => [
                'item_id' => 133734841781257,
                'title' => '测试商品A',
                'skuInfos' => [
                    [
                        'kwaiSkuId' => 133734841781257,
                        'specification' => '绿色',
                        'skuNick' => 'SKUA00002',
                        'skuStock' => 100
                    ]
                ]
            ]
        ];
    }

    public function open_item_sku_stock_update()
    {
//        return [
//            "result" => 1016,
//            "code" => "802000",
//            "msg" => "流量限制",
//            "error_msg" => "触发限流，请调整调用频率",
//            "sub_code" => "802005",
//            "sub_msg" =>
//                "APP请求频率过高，请降低调用频率，[apiId:open.order.goods.split.deliver;appkey:ks666532747450825751]，MAX_QPS[100分]",
//            "request_id" => "745461421192125890",
//        ];
        return [
            'result' => 1
        ];
    }

    public function open_seller_order_fee_detail(Request $request)
    {
        $params = json_decode($this->requestData['param'], true);
        $orderId = $params['orderId'] ?? 0;
        return [
            "result" => 1,
            "msg" => "success",
            "error_msg" => "",
            "code" => "1",
            "data" => [
                "platformBearAmount" => 0,
                "sellerRecv" => 900,
                "discountFee" => 0,
                "oid" => (int)$orderId,
                "expressFee" => 0,
                "tradeInPayAfterPromoAmount" => 0,
                "sellerId" => 20259999,
                "totalFee" => 900,
                "productFeeInfoOuters" => [
                    [
                        "discountFee" => 0,
                        "originalPrice" => 900,
                        "price" => 900,
                        "num" => 1,
                        "id" => (int)$orderId,
                        "oid" => (int)$orderId,
                        "productMarketingInfoOuters" => [],
                        "skuId" => 133734841781257,
                    ],
                ],
                "merchantBearAmount" => 0,
                "governmentDiscount" => 0,
                "payChannelDiscountDetails" => [
                    [
                        "channelDetailDesc" => "快手支付营销",
                        "channelDetailDiscount" => 200,
                        "channelDetailKey" => "KS_PAY",
                    ],
                ],
                "allowanceExpressFee" => 0,
                "marketingInfoOuters" => [],
                "buyerPay" => 700,
                "payChannelDiscount" => 200,
                "platformAllowance" => 0,
            ],
            "requestId" => (string)time(),
            "sub_msg" => "",
            "sub_code" => "1",
        ];
    }

    public function open_order_goods_split_deliver()
    {
//        return [
//            'result' => 1016,
//            'error_msg' => '超出QPS限流'
//        ];
        return [
            'result' => 1,
            'message' => 'success'
        ];
    }

    public function open_seller_order_goods_logistics_append()
    {
//        return [
//            'result' => 1016,
//            'error_msg' => '超出QPS限流'
//        ];
        return [
            'result' => 1,
            'message' => 'success'
        ];
    }

    public function open_order_detail()
    {
//        $str = '{"result":1,"msg":"success","error_msg":"","code":"1","data":{"addressUpdateAuditInfo":{"timeoutOfAudit":0,"auditTime":0,"auditStatus":0},"orderBaseInfo":{"discountFee":3300,"buyerNick":"","payTime":1753841402273,"channel":"超级链接竞价","remindShipmentSign":0,"sellerOpenId":"f198f00daa62817014bf5724200f87a5","expressFee":0,"buyerImage":"","payType":2,"multiplePiecesNo":0,"expressCode":"","enableSplitDeliveryOrder":true,"validPromiseShipmentTimeStamp":1755137402273,"governmentDiscount":0,"disableDeliveryReasonCode":[],"cpsType":0,"promiseTimeStampOfDelivery":0,"riskCode":0,"theDayOfDeliverGoodsTime":120,"commentStatus":0,"sendTime":1753860448835,"tradeInPayAfterPromoAmount":0,"remindShipmentTime":0,"allowanceExpressFee":0,"status":30,"orderLabels":[],"remark":"","oid":2521102400307001,"shopNewBuyer":false,"privacyInfoAuthTime":0,"sellerNick":"好奇旗舰店","recvTime":1754724449892,"buyerOpenId":"f198f00daa62817014bf5724cfbccc38","refundTime":0,"carrierType":0,"orderTaxInfo":{"sellerBearAmount":0,"taxAmount":0},"platformNewBuyer":false,"updateTime":1754724451912,"preSale":1,"privacyInfoAuthStatus":0,"coType":0,"createTime":1753841350754,"totalFee":900,"allActivityType":[1,25],"sellerDelayPromiseTimeStamp":1755137402273,"payChannel":"ALIPAY","activityType":1,"carrierId":0,"priorityDelivery":false,"payChannelDiscount":0},"orderRefundList":[],"orderAddress":{"districtCode":140181,"town":"岔口乡","city":"太原市","townCode":140181203,"cityCode":1401,"provinceCode":14,"encryptedMobile":"$5ZoL0wgbEvxibV7IIzdYj2RygGMgt3oQn641pBisAHw=$Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESICTnpthAWU7jrisd+S9GUI8ZJqbUUUtx7A58w791r8Y5GhLzGK9ig9PEjGOrFnr07FbUbp8iILzEqv9Pln9oWkxwzO1QlgI9ELSjkhtYiR9NT4VW0dWdKAUwAQ==&Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESMAXyysd4r2NLBHJ+mNDet4fQ3+52pq35JHDdIJAcNjxJGHy6XBjrFeOKN9mDJUtGSRoSCP2ip1JsWfslPU2JjBkOBrKsIiBYr90tWkOuaqIaNrVA0IV6Qrm/cee0cAI10BOUbbgxQSgFMAE=$1$$","encryptedConsignee":"#s3jAJQPvJQPv#Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESIFT1AMEasgp34Q4qz2XKoPktPmwv+XOP0qfMPp3LSAwMGhJTLugJQg3WVx3F64Z0Ja7UYdsiIPvpR9SQCpzZ41uYbtl9hvpO2jDafiaGIUyR0ubefWxYKAUwAQ==&Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESMPrcwmr2gGj7ZOiIrelTwPSKmJh3PgMpPWyKLiyniN2euKWzml42+4Gmhe9Fxp5pHBoSCP2ip1JsWfslPU2JjBkOBrKsIiDAGwz/Kt7JRzD5hhpUtjGD6BaIKpAWpSdlDnbwt5Yx9SgFMAE=#1##","desensitiseConsignee":"王**","encryptedAddress":"~D7/q+NnvdVwmpePmEaV/iSno~Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESMNRPYAMj0VemY8egV8NNk9X/CXk6nIn7MttdQNouTnj7fGovX1yDxtggDqtipXGUDhoSplwErqgAFX84+t7HQyumZl7qIiBwF2wpnV3qQbTkO1OziAtJSrvlr+6Gz7BqZrN7VUT+MSgFMAE=&Ci1tZXJjaGFudC5vcGVuLnNlY3JldC5rZXkua3M2NjY1MzI3NDc0NTA4MjU3NTESMNzCcYl1Z0Tgtep1bcJYozmmdstBxMxYnWNPKWiCr2wAKmgzCA6rTNy6VTWdjgvj8RoSAoL5f2L/nB2+/hAZx9vyMXmPIiCYyL5c2iwifx0T7YVlYz7xqhlFQMLzxTp15yJ4Ifur4igFMAE=~1~~","province":"山西省","district":"古交市","desensitiseMobile":"1********46","desensitiseAddress":"**市关**"},"orderLogisticsInfo":[{"logisticsId":81697352594226,"expressNo":"319292600780914","expressCode":11},{"logisticsId":81695482918226,"expressNo":"319292697320372","expressCode":11}],"orderItemInfo":{"itemPicUrl":"https://p2-ec.ecukwai.com/bs2/image-kwaishop-product/ITEM_IMAGE-4191832039-d43f2dc32609425c99a95ccd231b535c.jpg","itemType":1,"discountFee":3300,"originalPrice":900,"itemTitle":"好奇夏季小桃裤元气裸感纸尿裤拉拉裤四包 db","orderItemId":958169428538226,"num":1,"itemExtra":{"brandName":"好奇/HUGGIES","energyLevel":"","categoryInfo":{"govCategory":"","itemCid":2643,"govCategoryCode":"","categoryName":"纸尿裤"},"productNo":""},"serviceInfo":{"serviceRule":"{\"refundRule\":\"5\",\"depositRule\":\"\",\"deliverGoodsIntervalTime\":1296000,\"saleFlag\":false,\"promiseDeliveryTime\":-1,\"theDayOfDeliverGoodsTime\":0,\"immediatelyOnOfflineFlag\":1,\"deliveryMethod\":\"logistics\",\"supportVerification\":-1,\"certMerchantCode\":\"\",\"certExpireType\":0,\"certStartTime\":0,\"certEndTime\":0,\"certExpDays\":0,\"orderPurchaseLimitType\":0,\"minOrderCount\":0,\"maxOrderCount\":0,\"servicePromise\":{\"freshRotRefund\":false,\"brokenRefund\":true,\"allergyRefund\":true,\"crabRefund\":false,\"weightGuarantee\":false},\"unavailableTimeRule\":{\"weeks\":[],\"holidays\":[],\"timeRanges\":[]},\"qualityInspection\":0,\"customerInfoType\":\"\",\"customerCertificateTypeList\":[],\"priceProtectDays\":0,\"deliveryTimeMode\":\"presale\",\"mixPromiseDeliveryTime\":-1,\"mixPresaleDeliveryTime\":[],\"serviceProviderPolicy\":{\"minAge\":0,\"maxAge\":0,\"days\":0,\"times\":0}}","freight":true,"freightProviderType":2,"firstOrderGuarantee":false,"compensateFake":{"times":10,"desc":"假一赔十","link":"https://ppg.viviv.com/doodle/lPUfkBfr.html?uni_src=other_secondary_page&hyId=jimu&bizId=jimu_lPUfkBfr&layoutType=4&noBackNavi=true&test=true"},"instantDelivery":0,"instantRefund":true,"serviceRuleInfo":{"refundRule":"5","depositRule":"","deliverGoodsIntervalTime":1296000,"theDayOfDeliverGoodsTime":0,"saleFlag":false,"promiseDeliveryTime":-1,"immediatelyOnOfflineFlag":1,"deliveryMethod":"logistics","supportVerification":-1,"certMerchantCode":"","certExpireType":0,"certStartTime":0,"certEndTime":0,"certExpDays":0},"freightProviderTypeDesc":"商家出资","showInsuranceRefuseTag":false,"insuranceRefuseReason":"","freightProviderExplainDesc":"该订单退货包运费服务的服务费由商家出资","buyExpensiveCompensateInfo":{"canDisplayTag":false}},"goodStoreCode":0,"warehouseCode":"","itemId":24422000444039,"relItemId":24422000444039,"relSkuId":0,"price":900,"itemLinkUrl":"https://app.kwaixiaodian.com/merchant/shop/detail?id=24422000444039&hyId=kwaishop&layoutType=4","skuNick":"4163-16*4","skuDesc":"纸尿裤M码52片*4包（12-22斤，4-6月）","goodsCode":"","skuId":133734841781257},"orderNote":{"sellerNote":["加急发货"],"orderNoteInfo":[{"note":"加急发货","flagTagCode":"red_flag_tag_order","createTime":1753841560423,"operatorName":"趣趣"}]},"orderDeliveryInfo":{"splitDeliveryOrder":false,"mergeDeliveryType":0,"deliveryNum":1,"enableAppendPackage":true,"totalPackageNum":2,"openAddressId":"EjBxYvtk7ai70a1QQB56v+foFfNyFhOzBRZQMxr+gJysLLakVaNTY097ciCd5M8C0UgoBTAG","maxPackageNum":50,"deliveryStatus":40,"packageNum":2},"orderFlag":{"flag":["red_flag_tag_order"]},"subOrderInfo":[]},"requestId":"755223642491677385","sub_msg":"","sub_code":"1"}';
//        return json_decode($str, true);

        $orderBaseInfo = [
            "oid" => 20210987654327,
            "payTime" => 1543843735000,
            "buyerImage" => "https://tx2.a.yximgs.com/uhead/AB/2019/10/28/17/B13123213123.jpg",
            "buyerOpenId" => "1234567",
            "buyerNick" => "赵四",
            "sellerOpenId" => "12098765",
            "sellerNick" => "张三",
            "expressFee" => 0,
            "discountFee" => 0,
            "totalFee" => 900,
            "status" => 10,
            "sendTime" => 1543843735000,
            "refundTime" => 1543843735000,
            "createTime" => 1543843735000,
            "updateTime" => 1543843735000,
            "remark" => "买家留言",
            "theDayOfDeliverGoodsTime" => 0,
            "promiseTimeStampOfDelivery" => 1543843735000,
            "activityType" => 1,
            "cpsType" => 1,
            "validPromiseShipmentTimeStamp" => 1543843735000,
            "preSale" => 0,
            "recvTime" => 1543843735000,
            "coType" => 0,
            "commentStatus" => 1,
            "payType" => 1,
            "riskCode" => 0,
            "orderPoiInfo" => [],
            "shopNewBuyer" => true,
            "platformNewBuyer" => true,
            "orderTaxInfo" => [],
            "payChannel" => "1",
            "sellerDelayPromiseTimeStamp" => 1643843735000,
            "carrierType" => 1,
            "carrierId" => 16789,
            "privacyInfoAuthStatus" => 0,
            "privacyInfoAuthTime" => 0,
            "priorityDelivery" => true,
            "remindShipmentSign" => 3,
            "remindShipmentTime" => 1643843735000,
            "orderSellerRoleInfo" => [],
            "disableDeliveryReasonCode" => [],
            "multiplePiecesNo" => 20210987654327,
            "allActivityType" => [],
            "orderLabels" => [],
            "enableSplitDeliveryOrder" => false,
            "allowanceExpressFee" => 0,
            "payChannelDiscount" => 0,
            "tradeInPayAfterPromoAmount" => 0,
            "governmentDiscount" => 0,
            "govIndustryPromoInfo" => []
        ];


        $flag_tags = [
            'red_flag_tag_order', 'yellow_flag_tag_order', 'green_flag_tag_order',
            'blue_flag_tag_order', 'purple_flag_tag_order', 'grey_flag_tag_order'
        ];
        $orderNoteInfos = [];
        foreach ($flag_tags as $key => $flag_tag) {
            $orderNoteInfos[] = [
                "createTime" => sprintf('%s000%s', date('Ymd'), $key),
                "note" => sprintf('订单备注：%s_%s', $flag_tag, Str::random(10)),
                "flagTagCode" => $flag_tag,
                "operatorName" => "客服小鱼"
            ];
        }

        return [
            'result' => 1,
            'message' => 'success',
            'data' => [
                "orderBaseInfo" => $orderBaseInfo,
                "orderItemInfo" => [
                    "skuId" => 133734841781257,
                    "relSkuId" => 1209876543,
                    "skuDesc" => "水果",
                    "skuNick" => "12098765",
                    "itemId" => 10987654,
                    "relItemId" => 120987766,
                    "itemTitle" => "西瓜",
                    "itemLinkUrl" => "https://...",
                    "itemPicUrl" => "https://...",
                    "num" => 1,
                    "originalPrice" => 900,
                    "discountFee" => 0,
                    "price" => 900,
                    "itemType" => 1,
                    "itemPrevInfo" => [],
                    "goodsCode" => "123",
                    "warehouseCode" => "111",
                    "orderItemId" => 123,
                    "goodStoreCode" => 13211212321,
                    "serviceInfo" => [],
                    "itemExtra" => []
                ],
                "orderRefundList" => [],
                "orderLogisticsInfo" => [],
                "orderNote" => [
                    'orderNoteInfo' => $orderNoteInfos
                ],
                "orderAddress" => [
                    "encryptedConsignee" => "abcdef",
                    "desensitiseConsignee" => "里*",
                    "encryptedMobile" => "abcdef",
                    "desensitiseMobile" => "1********36",
                    "provinceCode" => 123455,
                    "province" => "北京",
                    "cityCode" => 120987,
                    "city" => "北京",
                    "districtCode" => 10000,
                    "district" => "上地",
                    "townCode" => 0,
                    "town" => "西北旺镇",
                    "encryptedAddress" => "abcdef",
                    "desensitiseAddress" => "快*",
                    "rechargeAccount" => [],
                    "coordinateInfo" => []
                ],
                "orderFlag" => [],
                "orderStepInfo" => [],
                "orderCustomizedInfo" => [],
                "orderCpsInfo" => [],
                "addressUpdateAuditInfo" => [],
                "orderDeliveryInfo" => [
                    "maxPackageNum" => 10,
                    "enableAppendPackage" => true,
                    "totalPackageNum" => 1,
                    "deliveryNum" => 1,
                    "packageNum" => 1,
                    "serialNumberInfo" => [
                        "maxPackageNum" => 10,
                        "enableAppendPackage" => true,
                        "totalPackageNum" => 1,
                        "deliveryNum" => 1,
                        "packageNum" => 1,
                        "serialNumberInfo" => [],
                        "splitDeliveryOrder" => false,
                        "deliveryStatus" => 10,
                        "mergeDeliveryType" => 1,
                        "openAddressId" => "1"
                    ],
                    "splitDeliveryOrder" => false,
                    "deliveryStatus" => 10
                ],
                "subOrderInfo" => []
            ]
        ];
    }
}
